const colCache = require('../utils/col-cache');

class RangeManager {
  constructor(worksheet, range) {
    this.sheet = worksheet;
    this._top = range.top;
    this._left = range.left;
    this._bottom = range.bottom;
    this._right = range.right;
    this.cells = this._collectCells();
  }

  _collectCells() {
    const { sheet, _top, _left, _bottom, _right } = this;
    const cells = [];
    for (let i = _top; i <= _bottom; i++) {
      const row = sheet.getRow(i);
      for (let j = _left; j <= _right; j++) {
        const cell = row.getCell(j);
        cells.push(cell);
      }
    }
    return cells;
  }

  top(top) {
    this._top = top;
    this.cells = this._collectCells();
    return this;
  }

  left(left) {
    if (typeof left === 'string') {
      left = colCache.l2n(left);
    }
    this._left = left;
    this.cells = this._collectCells();
    return this;
  }

  bottom(bottom) {
    this._bottom = bottom;
    this.cells = this._collectCells();
    return this;
  }

  right(right) {
    if (typeof right === 'string') {
      right = colCache.l2n(right);
    }
    this._right = right;
    this.cells = this._collectCells();
    return this;
  }

  toString() {
    return `sheet: ${this.sheet.name} 
       top: ${this._top} 
       left: ${this._left} 
       bottom: ${this._bottom} 
       right: ${this._right}`;
  }

  eachCell(fn) {
    this.cells.forEach((cell) => fn(cell));
    return this;
  }

  merge() {
    this.sheet.mergeCells(this._top, this._left, this._bottom, this._right);
    return this;
  }

  unMerge() {
    this.sheet.unMergeCells(this._top, this._left, this._bottom, this._right);
    return this;
  }

  setStyle(style) {
    this.eachCell((cell) => cell.style = style);
    return this;
  }

  set style(style) {
    this.setStyle(style);
  }

  safeStyle(fn) {
    this.eachCell((cell) => cell.safeStyle(fn));
    return this;
  }
}

module.exports = RangeManager;
